// const OSS = require('ali-oss');
import {
  getSTS,
  getOSS,
  postProfile,
} from '@/utils/api';

export default {
  data() {
    return {
      single: false, // 单个认证
      config: '',
      userId: '',
      client: '',
      names: [],
      imgList: [],
      currentIndex: 0, // 当前上传图片索引
      previewImg: '', // 预览图片地址
    }
  },
  mounted() {
    this.queryOSS(); // 获取oss上传签名

    const userInfo = uni.getStorageSync("userInfo");
    this.userId = userInfo.id;
  },
  methods: {
    // async querySTS() {
    //   let res = await getSTS({
    //     key: 'identification'
    //   });

    //   console.log(res)
    //   const token = res.data.token;
    //   const bucket = res.data.bucket;

    //   this.client = new OSS({
    //     accessKeyId: token.AccessKeyId, // 后台的临时签名ID
    //     accessKeySecret: token.AccessKeySecret, // 后台的临时签名密钥
    //     stsToken: token.SecurityToken,
    //     region: bucket.region,
    //     bucket: bucket.name
    //   });
    //   this.client.get('H_5dc0290382aae00150a89e2e-workPermit-1575461498018.png')
    // },
    // 获取oss上传签名
    async queryOSS() {
      let res = await getOSS({
        key: 'identification'
      });
      this.config = res.data
    },
    // 切换popup
    togglePopup(toggle, index) {
      this.currentIndex = index == undefined ? 0 : Number(index);
      if (toggle === 'open') {
        // this.currentIndex = index
        this.$refs.upload.open()
      } else if (toggle === 'close') {
        this.$refs.upload.close()
      }
    },
    // 拍照
    onTakeImg(type) {
      count: 1,
      uni.chooseImage({
        sourceType: ['camera'], //使用相机
        success: (res) => {
          this.handleChooseTaskImg(res.tempFilePaths[0], type)
        }
      });
    },
    // 上传照片
    onChooseImg(type) {
      uni.chooseImage({
        count: 1,
        sourceType: ['album'], //从相册选择
        success: (res) => {
          this.handleChooseTaskImg(res.tempFilePaths[0], type)
        }
      });
    },
    // 选择图片
    handleChooseTaskImg(path, type) {
      // 上传图片到oss
      this.uploadOSS(type, path).then(res => {
        // 解决改变数组中的元素不发生双向数据绑定
        let list = JSON.parse(JSON.stringify(this.imgList))
        list[this.currentIndex] = path; // 预览图片
        this.imgList = list;

        this.togglePopup('close', this.currentIndex)
        console.log(JSON.stringify(this.imgList))
        uni.showToast({
          title: '图片上传成功！',
          icon: 'none',
          duration: 2000
        });
        this.names[this.currentIndex] = res.data;
      }).catch(err => {
        uni.showToast({
          title: '图片上传失败,请重新上传！',
          icon: 'none',
          duration: 2000
        });
        this.togglePopup('close', this.currentIndex)
        console.log(JSON.stringify(err))
        console.log('ERRRRRR')
      });
    },
    // 预览
    onPrview(index) {
      index = index == undefined ? 0 : Number(index);
      if (this.imgList[index]) {
        this.previewImg = this.imgList[index];
        this.$refs.preview.open();
      }
    },
    // 上传文件到oss
    uploadOSS(type, path) {
      const config = this.config;
      const timestamp = new Date().getTime();
      const name = this.userId + '-' + type + '-' + timestamp + this.getFileExtendingName(path);
      console.log(name)
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: config.host,
          filePath: path,
          name: 'file',
          formData: {
            'key': name,
            'policy': config.policy,
            'OSSAccessKeyId': config.accessid,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'expire': Number(config.expire),
            'signature': config.signature,
          },
          success: (res) => {
            console.log(JSON.stringify(res))
            if (res.statusCode === 200) {
              res.data = name;
              resolve(res)
            } else {
              reject(res)
            }
          },
          fail: (err) => {
            reject(err)
          }
        });
      })
    },
    // 文件扩展名匹配正则
    getFileExtendingName(path) {
      var reg = /\.[^\.]+$/;
      var matches = reg.exec(path);
      if (matches) {
        return matches[0];
      }
      return '';
    },
    // 认证
    putAuth(type) {
      const params = {
        type: type,
        names: this.names
      };
      let identities = uni.getStorageSync('identities') || [];
      identities.push(params);
      uni.setStorageSync('identities', identities);
      if(this.single) {
        this.profileSingle();
      } else {
        uni.setStorageSync('auth_' + type, '99');
        uni.navigateBack();
      }
    },
    // 单个图片认证
    async profileSingle() {
      let identities = uni.getStorageSync('identities');
      let res = await postProfile({
        identities: identities
      });
      if (res.status === 0) {
        uni.removeStorageSync('identities');
        uni.showToast({
          title: '上传成功！',
          icon: 'none',
          duration: 2000
        });
        setTimeout(function() {
          uni.navigateBack();
        }, 2000);
      } else {
        // 提交失败
        uni.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
}
